package cn.hfatec.shms.system.document.service;

import cn.hfatec.JsonResponse;
import cn.hfatec.Page;
import cn.hfatec.Table;
import cn.hfatec.app.AppContext;
import cn.hfatec.base.BaseDao;
import cn.hfatec.shms.constants.ShmsConstant;
import cn.hfatec.shms.constants.ShmsProperties;
import cn.hfatec.shms.exception.NotAuthException;
import cn.hfatec.shms.system.document.dao.DocumentDao;
import cn.hfatec.shms.system.document.model.Document;
import cn.hfatec.shms.system.document.model.DocumentParams;
import cn.hfatec.shms.system.user.model.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.util.Date;
import java.util.HashMap;


/**
 *
 * @author hfatec
 * @version 1.0
 *
 * the JAVA code is generate by middlegen
 *
 */
@Service("DocumentService")
public class DocumentService {

    public static final String BEAN_ID = "DocumentService";

    //注入Dao层
    @Resource(name = "DocumentDao")
    private DocumentDao documentDao;

    //注入BaseDao
    @Resource(name = "BaseDao")
    private BaseDao baseDao;

    /**
     *
     * 查询数据
     *
     * @param documentParams
     * @param page
     *
     */
    @Transactional
    public Table queryDocumentTable(DocumentParams documentParams, Page page){

        HashMap<String, Object> params = new HashMap<String, Object>();
        params.put("params", documentParams);
        return baseDao.queryTableByPage("queryDocument", params, page);
    }

    /**
     * 插入数据
     * @param file
     * @param request
     */
    @Transactional
    public String saveDocument(MultipartFile file,HttpServletRequest request) throws NotAuthException, IOException {
        //获取配置的上传文件路径
        ShmsProperties shmsProperties = AppContext.getBean("shmsProperties", ShmsProperties.class);
        String realPath = shmsProperties.getUploadPath();
        String documentPath = shmsProperties.getUploadDocumentPath();
        String uploadFilePath = realPath+"\\"+documentPath;
        User user = (User) request.getSession().getAttribute(ShmsConstant.LOGIN_USER_SESSION_NAME);
        if (user == null) {
            throw new NotAuthException("用户未授权");
        }
        InetAddress addr = InetAddress.getLocalHost();

        String fileName = file.getOriginalFilename();//获取文件名称
        File headPath = new File(uploadFilePath);//服务器文件夹保存路径
        if (!headPath.exists()) {//判断文件夹是否存在，没有存在则创建新文件夹
            headPath.mkdirs();//创建文件夹
        }
        InputStream in = file.getInputStream();
        FileOutputStream out = new FileOutputStream(headPath + "/" + fileName);//文件保存路径
        byte[] buffer = new byte[1024];
        int byteread = 0;
        while ((byteread = in.read(buffer)) > 0) {
            //写入文件
            out.write(buffer, 0, byteread);
        }
        //关闭输入输出流
        in.close();
        out.close();
        //保存上传记录
        Document document = new Document();
        document.setOperationDate(new Date());//操作时间
        document.setOperationIp(addr.getHostAddress().toString());//操作Ip
        document.setOperationOrgId(user.getOrgId());
        document.setDocUrl(fileName);
        document.setOperationUserId(user.getLoginName());
        Document document1 = documentDao.getDocumentByFileName(document.getDocUrl());
        if (document1 != null) {
            return new JsonResponse<String>(JsonResponse.RETURN_FAILURE, "文件"+fileName+"已上传！", "").toString();
        } else {
            documentDao.insert(document);
        }
        return new JsonResponse<String>(JsonResponse.RETURN_SUCCESS, "文件上传成功").toString();
    }
}